package com.yunji.cabinet.business;

import com.yunji.base.cache.BaseCache;
import com.yunji.base.domain.BelongDO;
import com.yunji.cabinet.bo.CabinetTemplateBO;
import com.yunji.cabinet.bo.CapacityCeilingBO;
import com.yunji.cabinet.cache.CabinetCache;
import com.yunji.cabinet.context.calculate.CabinetCalculate;
import com.yunji.cabinet.domain.CabinetTemplateDO;
import com.yunji.cabinet.domain.CabinetTemplateCellDO;
import com.yunji.cabinet.dto.CabinetFiledDTO;
import com.yunji.cabinet.dto.TemplateDTO;
import com.yunji.cabinet.service.ICabinetTemplateCellService;
import com.yunji.cabinet.service.ICabinetTemplateService;
import com.yunji.cabinet.vo.TemplateCellVO;
import com.yunji.cabinet.vo.TemplateVO;
import com.yunji.common.base.BaseBusiness;
import com.yunji.common.enums.common.UserType;
import com.yunji.common.model.cache.ContainerTypeCacheDTO;
import com.yunji.common.model.cache.ProductAgentCacheDTO;
import com.yunji.common.model.dto.LoginInfo;
import com.yunji.common.utils.ConvertDataUtil;
import com.yunji.common.utils.bean.BeanUtils;
import com.yunji.product.cache.ProductCache;
import com.yunji.system.service.TokenService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Package com.yunji.web.business
 * FileName:	CabinetTemplateBusiness.java
 * Copyright:	Copyright © 2024 云集互联 All Rights Reserved
 * Company:		云集互联
 * @version: 1.0
 * @since: JDK 1.8.0_202
 * Create at:   2024-04-07 16:57:15
 * Description:
 * 货柜模板业务处理
 * Modification History:
 * Author					Date						Version			Description
 * --------------------------------------------------------------------------------
 * HuaAo				2024-04-07 16:57:15			1.0				1.0 Version
 */
@Component
public class CabinetTemplateBusiness extends BaseBusiness {

    @Resource
    ICabinetTemplateService templateService;

    @Resource
    ICabinetTemplateCellService templateCellService;

    @Resource
    TokenService tokenService;

    /**
     * @param params 参数信息
     * @Title handleParam
     * @Desc 处理用户参数信息
     * @Date 2024-09-09 16:19:42.109
     */
    private void handleParam(CabinetFiledDTO params) {
        LoginInfo user = tokenService.getUser();
        Long belongId = user.getBelongId();
        String userType = user.getUserType();
        String userText = UserType.getText(userType);
        logs.info("【货柜模板】当前用户所属ID:{}, 用户类型={}:{}", belongId, userType, userText);

        if (BeanUtils.equals(userType, UserType.AGENT.getCode())) {
            params.setParentId(belongId);
        }
        if (BeanUtils.equals(userType, UserType.SITE.getCode(), UserType.STAFF.getCode())) {
            params.setBelongId(belongId);
        }
    }

    public CabinetTemplateBO selectTemplateById(Long id) {
        return templateService.select(id);
    }


    @Transactional
    public TemplateVO selectTemplateVOById(Long templateId) {
        CabinetTemplateBO templateBO = templateService.select(templateId);
        List<CabinetTemplateCellDO> cellList = templateBO.getCellList();
        List<Long> productIds = ConvertDataUtil.list2FieldList(cellList, CabinetTemplateCellDO::getProductId);
        TemplateVO templateVO = new TemplateVO();
        BeanUtils.clone(templateBO.getCabinetTemplate(),templateVO);
        List<ProductAgentCacheDTO> paList = ProductCache.getProductAgent(templateBO.getCabinetTemplate().getBelongId(), productIds);
        Map<Long, ProductAgentCacheDTO> productMap = ConvertDataUtil.list2Map(paList, ProductAgentCacheDTO::getProductId);
        List<TemplateCellVO> cellVOList = new ArrayList<>();
        for (CabinetTemplateCellDO cellDO : cellList) {
            TemplateCellVO vo = new TemplateCellVO();
            Long productId = cellDO.getProductId();
            ProductAgentCacheDTO cacheDTO = productMap.get(productId);
            vo.setProductName(cacheDTO.getProductName());
            vo.setProductId(productId);
            vo.setAlbumPics(ProductCache.getAlbumPics(productId));
            vo.setCeilingQuantity(CabinetCalculate.getCapacityCeiling(new CapacityCeilingBO(templateBO.getCabinetTemplate().getTypeCode(),productId)).intValue());
            vo.setPrice(cacheDTO.getPrice());
            vo.setOrdinal(cellDO.getOrdinal());
            vo.setCostPrice(cacheDTO.getCostPrice());
            vo.setDiscountPrice(cacheDTO.getDiscountPrice());
            vo.setProductType(ProductCache.getProductType(productId));
            cellVOList.add(vo);
        }
        templateVO.setList(cellVOList);
        return templateVO;
    }

    /**
     * @Title checkContainerShape
     * @Desc 校验货柜形状信息
     * @Date 2024-04-09 14:51:38
     * @Param template 货柜模版
     */
    private void checkContainerShape(CabinetTemplateDO template) {
        ContainerTypeCacheDTO type = CabinetCache.getContainerType(template.getTypeCode());
        List<CabinetTemplateCellDO> cells = template.getList();
        Assert.isTrue(BeanUtils.isNotNull(cells), "请添加模板商品信息");
        int count = cells.size();
        Assert.isTrue((type.getNums() == count), "模板货柜商品请补充完整");
        template.setNums(type.getNums());
    }

    @Transactional
    public Long create(CabinetTemplateDO template) {
        checkContainerShape(template);
        List<CabinetTemplateCellDO> cells = template.getList();

        LoginInfo user = tokenService.getUser();
        Long belongId = user.getBelongId();

        String userType = user.getUserType();
        String userText = UserType.getText(userType);
        logs.info("【货柜模板】当前用户所属ID:{},用户类型={}:{}", belongId, userType, userText);

        BelongDO belong = BaseCache.getBelong(belongId);
        Assert.isTrue(BeanUtils.isNotNull(belong), "未找到用户所属单位信息");
        Long siteId = belong.getSiteId();
        Long agentId = belong.getAgentId();
        template.setAgentId(agentId);
        template.setSiteId(siteId);
        template.setBelongId(belongId);
        template.setUserType(userType);

        Assert.isTrue(templateService.create(template), "添加失败");
        for (CabinetTemplateCellDO cell : cells) {
            cell.setTemplateId(template.getTemplateId());
            CabinetTemplateCellDO create = new CabinetTemplateCellDO();
            BeanUtils.clone(cell, create);
            Assert.isTrue(templateCellService.create(create), "添加失败");
        }
        return template.getTemplateId();
    }

    @Transactional
    public boolean update(TemplateDTO template) {
        Long templateId = template.getTemplateId();
        logs.info("【货柜模板】货柜模板ID:{}", templateId);
        Assert.isTrue(BeanUtils.isNotNull(templateId), "未找到模板信息");

        CabinetTemplateDO createTemplate = new CabinetTemplateDO();
        BeanUtils.clone(template, createTemplate);
        checkContainerShape(createTemplate);
        List<CabinetTemplateCellDO> cells = template.getList();

        Assert.isTrue(templateService.update(createTemplate), "更新失败");
        Assert.isTrue(templateCellService.deleteByTemplateIds(template.getTemplateId()), "更新失败");
        for (CabinetTemplateCellDO cell : cells) {
            cell.setTemplateId(templateId);
            CabinetTemplateCellDO create = new CabinetTemplateCellDO();
            BeanUtils.clone(cell, create);
            templateCellService.create(create);
        }
        return true;
    }

    /**
     * @param ids 模板ID数组
     * @Title delete
     * @Desc 删除模板信息
     * @Date 2024-08-26 14:50:42.310
     */
    @Transactional
    public void delete(Long... ids) {
        Assert.isTrue(templateCellService.deleteByTemplateIds(ids), "删除失败");
        Assert.isTrue(templateService.delete(ids), "删除失败");
    }

    /**---------------------------------------------搜索栏-----------------------------------------------*/

    /**
     * @param createName 创建人名称
     * @Title searchCreateName
     * @Desc 创建人搜索
     * @Date 2024-08-24 16:15:10.081
     * @Return List<String> 匹配名称
     */
    public List<String> searchCreateName(String createName) {
        Assert.isTrue((createName.length() <= 15), "输入的账号名称不合规");

        CabinetFiledDTO params = new CabinetFiledDTO();
        params.setSearchFiled("t.create_name");
        params.setCreateName(createName);
        handleParam(params);
        List<String> list = templateService.searchTableField(params);
        return BeanUtils.isNotNull(list) ? list : Collections.emptyList();
    }

}
